import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
//服务器端处理过程类
public class Processor extends Thread{

	private Socket socket=null;
	private InputStream in = null;
	private PrintStream out=null;
	//定义服务器端根路径
	public final static String WebRoot="D:\\eclipse workplace";
	//处理类构造函数
	public Processor(Socket socket){
		
		this.socket= socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//处理类主方法
	public void Run(){
		
		System.out.println("处理了一个连接！");
		BufferedReader br= new BufferedReader(new InputStreamReader(in));
		//读取客户端发过来的信息
		try {
			String HttpInfo = br.readLine();
			String[] content = HttpInfo.split(" ");
			System.out.println("HttpMethod:"+content[0]+",GetPath:"+content[1]+",HttpVersion:"+content[2]);
			//开始判断路径是否存在，如果不存在，则返回错误提示信息；否则，提示正确的信息
			String RequestFile= content[1];
			File file = new File(WebRoot+RequestFile);
			//如果文件不存在，则给予客户端提示信息
			if(!file.exists()){
				
				ResponseErrorMessage(404,"请求的文件不存在！");
			}else{
				//如果文件存在，则返回执行
				ResponseOKMessage(file);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//返回客户端错误信息
	public void ResponseErrorMessage(int MessageNumber,String Message){
			out.println("http/1.1 "+MessageNumber+" "+Message);
			out.println("content-type:text/html;charset=utf-8");
			out.println("<html><head><title>WebServer信息</title></head>");
			out.println("<body>");
			out.println("服务器返回信息代码："+MessageNumber+"<br>");
			out.println("服务器返回信息内容："+Message+"<br>");
			out.println("</body>");
			out.println("</html>");
			out.flush();
			out.close();
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	//返回客户端正确信息
	public void ResponseOKMessage(File file){
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int)file.length()];
			in.read(content);
			out.println("http/1.1 200 FileOK");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
}
//end class
}